#include "syntaxhighlighter.h"
#include <QRegularExpression>

CppHighlighter::CppHighlighter(QTextDocument *parent)
    : QSyntaxHighlighter(parent) {
    setupRules();
}

void CppHighlighter::setupRules() {
    // 关键字格式（蓝色加粗）
    QTextCharFormat keywordFormat;
    keywordFormat.setForeground(Qt::darkBlue);
    keywordFormat.setFontWeight(QFont::Bold);

    // C++关键字列表
    QStringList keywords = {
        "class", "return", "if", "else", "for", "while", "do", "switch",
        "case", "break", "continue", "public", "private", "protected",
        "signals", "slots", "emit", "int", "float", "double", "char",
        "bool", "void", "true", "false", "nullptr", "auto", "const",
        "static", "virtual", "override", "final", "this", "new", "delete"
    };

    // 添加关键字规则
    for (const QString &keyword : keywords) {
        addRule("\\b" + keyword + "\\b", keywordFormat);
    }

    // 类型格式（紫色）
    QTextCharFormat typeFormat;
    typeFormat.setForeground(QColor(128, 0, 128));
    addRule("\\b[A-Z][A-Za-z0-9_]*\\b", typeFormat); // 大写开头的类型名

    // 字符串格式（绿色）
    QTextCharFormat stringFormat;
    stringFormat.setForeground(Qt::darkGreen);
    addRule(R"("(\\.|[^"\\])*")", stringFormat);

    // 单行注释格式（灰色斜体）
    QTextCharFormat commentFormat;
    commentFormat.setForeground(Qt::gray);
    commentFormat.setFontItalic(true);
    addRule("//[^\n]*", commentFormat);

    // 数字格式（红色）
    QTextCharFormat numberFormat;
    numberFormat.setForeground(Qt::darkRed);
    addRule("\\b[0-9]+\\b", numberFormat);
    addRule("\\b0[xX][0-9a-fA-F]+\\b", numberFormat); // 十六进制

    // ===== 新增：预处理指令高亮=====
    QTextCharFormat preprocessorFormat;
    preprocessorFormat.setForeground(QColor(128, 0, 64));  // 深紫色
    preprocessorFormat.setFontItalic(true);
    addRule("^\\s*#\\s*[a-zA-Z]+", preprocessorFormat);  // 匹配 #include, #define 等

    // ===== 新增：函数名高亮 =====
    QTextCharFormat functionFormat;
    functionFormat.setForeground(QColor(0, 100, 0));  // 深绿色
    functionFormat.setFontWeight(QFont::Bold);
    addRule("\\b[A-Za-z_][A-Za-z0-9_]*(?=\\s*\\()", functionFormat);  // 匹配函数名
}

void CppHighlighter::addRule(const QString &pattern, const QTextCharFormat &format) {
    HighlightRule rule;
    rule.pattern = QRegularExpression(pattern);
    rule.format = format;
    rules.append(rule);
}

void CppHighlighter::highlightBlock(const QString &text) {
    // 处理多行注释
    highlightMultiLineComments(text);

    // 应用其他规则
    for (const HighlightRule &rule : rules) {
        QRegularExpressionMatchIterator it = rule.pattern.globalMatch(text);
        while (it.hasNext()) {
            QRegularExpressionMatch match = it.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
}

void CppHighlighter::highlightMultiLineComments(const QString &text) {
    setCurrentBlockState(previousBlockState());

    QRegularExpression startExpression("/\\*");
    QRegularExpression endExpression("\\*/");

    int startIndex = 0;
    if (previousBlockState() != 1) {
        startIndex = text.indexOf(startExpression);
    }

    QTextCharFormat format;
    format.setForeground(Qt::gray);
    format.setFontItalic(true);

    while (startIndex >= 0) {
        QRegularExpressionMatch endMatch;
        int endIndex = text.indexOf(endExpression, startIndex, &endMatch);
        int commentLength;

        if (endIndex == -1) {
            setCurrentBlockState(1);
            commentLength = text.length() - startIndex;
        } else {
            commentLength = endIndex - startIndex + endMatch.capturedLength();
        }

        setFormat(startIndex, commentLength, format);
        startIndex = text.indexOf(startExpression, startIndex + commentLength);
    }
}
